import React from 'react';
import { inject, observer } from 'mobx-react';
import { TabPage, RouteLayout } from 'weaver-mobile-page';
import { toJS } from 'mobx';
import { Switch, Route, Redirect, Link } from 'react-router-dom';
import { Bubble, Tools, Toast, Icon, ActivityIndicator, Flex, ActionSheet, Modal } from 'weaver-mobile';
import WorkflowCenter from './list';
import { forwardViewForm, transQueryParams } from '../../util/common';

const Item = TabPage.Item;
const getLabel = Tools.getLabel;
const alert = Modal.alert;

const WORKFLOW_CENTER_STORE = 'WORKFLOW_CENTER_STORE';
@inject('workflowCenterStore')
@observer
class App extends React.Component {

  componentWillMount() {
    const { location } = this.props;
    let queryParams = transQueryParams(location) || {};
    const { setState, getTabs, nowViewScope, getDefaultTabs } = this.props.workflowCenterStore;
    const ss = Tools.ss;
    let hasretainCondition = false;
    if (!queryParams.hasOwnProperty("moduleid")) {
      queryParams.moduleid = 10;//以前发布到em和企业微信的应该都是moduleid等于10的默认流程中心应用，组件发布时，没有设置功能的应用不会传参到企微和钉钉，导致以前集成过去的的流程中心应用全都不带moduleid
    }
    if (window.sessionStorage && sessionStorage.getItem("__wf__list__retain__retainCondition")) {
      setState({ retainCondition: 1 });
      hasretainCondition = true;
    } else {
      setState({ retainCondition: 0 });
    }
    if (queryParams.requestname) {
      queryParams.requestname = decodeURI(queryParams.requestname)
    }
    setState({ queryParams })
    //if (queryParams.hasOwnProperty("moduleid")) {
    getTabs(queryParams.moduleid, hasretainCondition);
    // } else {
    //   getDefaultTabs();
    // }
  }

  changeTab(obj, index) {
    const { menuid, chageTable, setNowTab, nowStore } = this.props.workflowCenterStore;
    const path = obj.path;
    this.props.workflowCenterStore.currentBtn = '';
    // if (menuid !== -1) {
    chageTable(obj);
    setNowTab(index);
    // } else {
    //   const url = '/center/' + path;
    //   this.props.history.push(url);
    // }
  }

  isHighlight() {
    const { nowStore } = this.props.workflowCenterStore;
    const { searchAdvancedStore } = nowStore;
    let islight = false;
    if (searchAdvancedStore) {
      const formData = toJS(searchAdvancedStore.form.formData);
      Object.keys(formData).forEach((key) => {
        if (formData[key].value !== '' ||
          (Array.isArray(toJS(formData[key].value)) && formData[key].value.length > 0)) {
          islight = true;
        }
      });
    }
    return islight;
  }

  handleVisibleChange = visible => {
    const { setState } = this.props.workflowCenterStore;
    setState({ visible });
  };

  render() {
    const {
      tabs,
      changeCheck,
      visible,
      setState,
      getPage,
      showCheck,
      nowStore,
      nowScope,
      nowTab,
      showTab,
      canAddWF,
      canSubmit,
      isShowLoading,
      api_return_scopname,
      nowViewScope,
      nowScopeButtons = [],
      mobilecenter_button_manifestly,
      doReadIt,
      totalcount,
      queryParams,
    } = this.props.workflowCenterStore;

    let { menuid } = this.props.workflowCenterStore;
    menuid = parseInt(menuid, 10);
    const overlay = [];

    const centerButtonsTemp = [];
    const isShareSearch = (nowStore.searchAdvancedStore && nowStore.searchAdvancedStore.form && nowStore.searchAdvancedStore.form.formParams.viewcondition == '1')//共享流程列表，不显示左滑操作和批量提交等按钮
    //const isResourceCard = queryParams.hasOwnProperty("resourceid") && parseInt(queryParams.resourceid, 0) != 0;//是否是人力资源卡片过来的请求，屏蔽底部按钮及左滑操作
    nowScopeButtons && nowScopeButtons.map((button = {}, index) => {
      if ((isShareSearch && (button.key != 'batchSubmit' && button.key != 'batchAttention' && button.key != 'doReadIt')) || !isShareSearch) {
        if (centerButtonsTemp.length == 3) {
          const moreBtn = { 'key': 'more', 'buttonName': getLabel(17499, '更多') };
          centerButtonsTemp.push(moreBtn);
        }
        if (centerButtonsTemp.length <= 3) {
          centerButtonsTemp.push(toJS(button));
        }
        if (button.key === 'add') {//button统一走设置获取
          overlay.push(<Item key="0" value={button.key} singleWfid={button.singleWfid} data-seed="logId">
            <span >{button.buttonName}</span>
          </Item>)
        } else {
          overlay.push(<Item key="0" value={button.key} style={{ whiteSpace: 'nowrap' }}>
            <span >{button.buttonName}</span>
          </Item>)
        }
      }
    })

    let canBatchSupervise = false;
    let page = nowTab;
    // if (canAddWF) {
    //   overlay.push(<Item key="0" value="add" data-seed="logId">
    //     <span >{getLabel(16392, "新建流程")}</span>
    //   </Item>)
    // }

    // if (((menuid == -1 || api_return_scopname == "wfCenter") && page === 0 && visible) || canSubmit) {
    //   overlay.push(
    //     <Item key="1" value="batchSubmit" style={{ whiteSpace: 'nowrap' }}>
    //       <span className='' >{getLabel(17598, "批量提交")}</span>
    //     </Item>
    //   );
    // }

    // if (menuid == -1 || menuid > 0) {//menuid == 1 || menuid == 2 || menuid == 3{
    //   canBatchSupervise = true;
    //   overlay.push(
    //     <Item key="2" value="batchAttention" style={{ whiteSpace: 'nowrap' }}>
    //       <span className='' >{getLabel(503955, '批量关注')}</span>
    //     </Item>
    //   );

    //   /*if(!(menuid == 2 && page == 2)){//已办中的已归档，不显示批量督办
    //     overlay.push (
    //       <Item key="3" value="batchSupervise" style={{whiteSpace: 'nowrap'}}>
    //         <span className='' >{getLabel(84561,"批量督办")}</span>
    //       </Item>
    //     );
    //   }*/
    // }
    const Highlight = nowStore.islight;
    const color = Highlight ? '#55B1F9' : '';
    const searchPath = `${nowStore.path}/SearchAdvanced`;
    let isShowPopover = !(overlay.length <= 0 || mobilecenter_button_manifestly == 1);
    //if ((overlay.length <= 0 || mobilecenter_button_manifestly == 1)) isShowPopover = false;
    if (tabs && tabs.length > 0) {
      return (
        <div style={{ boxSizing: "border-box", paddingBottom: (centerButtonsTemp && centerButtonsTemp.length > 0) ? "47px" : "0px", overflow: "hidden", height: "100%" }}>
          <div>
            {showTab && <TabPage
              tabProps={{ onChange: this.changeTab.bind(this), page: page }}
              popover={isShowPopover}
              popoverProps={{
                onVisibleChange: this.handleVisibleChange.bind(this),
                visible,
                onSelect: (node, index) => {
                  const type = node.props.value;
                  const singleWfid = node.props.singleWfid || '';
                  if (type == 'add') {//新建流程
                    // if (singleWfid == '') {//直接跳转新页面，不清空
                    //   setState({ visible: false, leftTreeValueArray: [] });
                    //   nowStore.clear();
                    //   if (
                    //     nowStore.searchAdvancedStore &&
                    //     nowStore.searchAdvancedStore.form
                    //   ) {
                    //     nowStore.searchAdvancedStore.form.resetFields();
                    //   }
                    // }
                    setState({ visible: false });
                    this.doLinktoAddRequest({ moduleid: menuid, singleWfid: singleWfid });
                  } else {
                    if (this.props.workflowCenterStore.currentBtn != type && type != 'doReadIt') {//重新刷新check框--全部已读操作不刷新
                      this.props.workflowCenterStore.onSearch({}, type);
                      this.props.workflowCenterStore.currentBtn = type;
                    }
                    if (type == 'batchSubmit') {//批量提交
                      if (!showCheck) {
                        changeCheck(true);
                        setState({ visible: false });
                      } else {
                        setState({ visible: false });
                      }
                    } else if (type == 'batchSupervise') {//批量督办
                      changeCheck(true);
                      setState({ visible: false });
                    } else if (type == 'batchAttention') {
                      changeCheck(true);
                      setState({ visible: false });
                    } else if (type == 'doReadIt') {
                      setState({ visible: false });
                      alert(' ', getLabel(386173, '确定要将当前列表全部') + totalcount + getLabel(386174, "条数据都标记为已读吗？"), [
                        { text: getLabel(31129, '取消'), onPress: () => { } },
                        { text: getLabel(826, '确定'), onPress: () => doReadIt({ opertype: "batch", dataKey: nowStore.listViewStore.dataKey, fromQuickSearch: "false" }) },
                      ])
                    }
                    this.props.workflowCenterStore.popSelectKey = '1'
                  }
                },
                overlay,
              }}
              tabs={tabs}
            />}
          </div>

          <Switch>
            <Route path="/center/doing" component={WorkflowCenter} />
            <Route path="/center/done" component={WorkflowCenter} />
            <Route path="/center/mine" component={WorkflowCenter} />
            <Route path="/center/all" component={WorkflowCenter} />
            <Route path="/center/doneFinish" component={WorkflowCenter} />
            <Route path="/center/flowCS" component={WorkflowCenter} />
            <Route path="/center/attentionAll" component={WorkflowCenter} />
            <Redirect exact path="/center" to={{ pathname: '/center/doing' }} />
          </Switch>

          {/* 应用底部按钮 */}
          <div style={{ backgroundColor: "#F8F8F8" }}>
            {centerButtonsTemp && centerButtonsTemp.length > 0 && mobilecenter_button_manifestly == 1 &&
              <Flex className='wf-bottomOperate-container' justify="center" align='center'>
                {centerButtonsTemp.map((button = {}, index) => {
                  const { key, buttonName, flex = 4 } = button;
                  if (key == "more") {
                    button.buttonFun = () => {
                      this.showmoreBtn(nowScopeButtons);
                    }
                  } else {
                    button.buttonFun = () => {
                      this.doWfCenterBtnClick(button);
                    }
                  }
                  return (
                    <Flex.Item key={index} onClick={button.buttonFun}
                      className={`sign-bottom-item ${index < centerButtonsTemp.length - 1 ? 'sign-bottom-right-border' : ''}`}
                      style={{ flex }}
                    >

                      {<span className='item-showname'>{buttonName}</span>}
                    </Flex.Item>
                  )
                })
                }
              </Flex>
            }
          </div>

          {isShowLoading && <ActivityIndicator
            toast
            text={getLabel(500408, "加载中...")}
            animating={isShowLoading}
          />}

        </div>
      );
    } else {
      return (<div></div>);
    }
  }

  /**
   * 跳转到新建流程
   */
  doLinktoAddRequest(newReqParmas = {}) {
    const { setRetainCondition } = this.props.workflowCenterStore;
    setRetainCondition();
    if (newReqParmas.singleWfid && newReqParmas.singleWfid != '') {
      forwardViewForm({ iscreate: 1, workflowid: newReqParmas.singleWfid }, this.forwadCallback4NewFlow);//打开表单统一入口
    } else {
      this.props.history.push({ pathname: '/add', params: { moduleid: newReqParmas.moduleid } });
    }
    //this.props.history.push({ pathname: '/add'});
  }

  forwadCallback4NewFlow = (arg = {}) => {
    const { onSearch, showCheck } = this.props.workflowCenterStore;
    if (typeof arg === "string") {
      arg = JSON.parse(arg);
    }
    const { isReturn = false, iscreate = 0 } = arg;
    if (isReturn || (!isReturn && showCheck)) {//走的返回
      if (!isReturn || iscreate != 1) {//可能存在打开表单还未加载出来就点了返回  这种情况也暂不刷新
        onSearch({ notClearSelectedRowKeys: true });//不清空selectedRowKeys
      }
    } else {//走的提交
      onSearch();
    }
  }

  doWfCenterBtnClick(btn) {
    const {
      changeCheck,
      setState,
      showCheck,
      doReadIt,
      nowStore,
      totalcount,
      menuid
    } = this.props.workflowCenterStore;

    const type = btn.key;
    if (type == 'add') {//新建流程
      // if (!btn.singleWfid || btn.singleWfid == '') {//直接跳转新页面，不清空
      //   setState({ visible: false, leftTreeValueArray: [] });
      //   nowStore.clear();
      //   if (
      //     nowStore.searchAdvancedStore &&
      //     nowStore.searchAdvancedStore.form
      //   ) {
      //     nowStore.searchAdvancedStore.form.resetFields();
      //   }
      // }
      this.doLinktoAddRequest({ moduleid: menuid, singleWfid: btn.singleWfid });
    } else {
      if (type != 'doReadIt' && type != 'cancel') {//重新刷新check框--全部已读操作不刷新
        this.props.workflowCenterStore.onSearch({}, type);
        this.props.workflowCenterStore.currentBtn = type;
      }
      if (type == 'batchSubmit') {//批量提交
        if (!showCheck) {
          changeCheck(true);
          setState({ visible: false });
        } else {
          setState({ visible: false });
        }
      } else if (type == 'batchAttention') {
        changeCheck(true);
        setState({ visible: false });
      } else if (type == 'doReadIt') {
        alert(' ', getLabel(386173, '确定要将当前列表全部') + totalcount + getLabel(386174, "条数据都标记为已读吗？"), [
          { text: getLabel(31129, '取消'), onPress: () => { } },
          { text: getLabel(826, '确定'), onPress: () => doReadIt({ opertype: "batch", dataKey: nowStore.listViewStore.dataKey, fromQuickSearch: "false" }) },
        ])
      }
      this.props.workflowCenterStore.popSelectKey = '1'
    }
  }

  showmoreBtn(centerButtons = []) {
    const btns = [];
    const centerButtonsNew = toJS(centerButtons || []);
    centerButtonsNew.map(v => {
      btns.push({
        content: v.buttonName,
        key: v.key,
        singleWfid:v.singleWfid
      });
    });
    btns.push({ content: getLabel(31129, '取消'), key: "cancel" });
    const isIPhone = new RegExp('\\biPhone\\b|\\biPod\\b', 'i').test(window.navigator.userAgent);
    let wrapProps;
    if (isIPhone) {
      wrapProps = {
        onTouchStart: e => e.preventDefault(),
      };
    }
    ActionSheet.showActionSheetWithOptions({
      options: btns,
      cancelButtonIndex: btns.length - 1,
      destructiveButtonIndex: btns.length - 1,
      maskClosable: true,
      'data-seed': 'logId',
      wrapProps,
    },
      (buttonIndex) => {
        if (buttonIndex != btns.length && buttonIndex != -1) {
          let button = btns[buttonIndex];
          this.doWfCenterBtnClick(button);
        }
      }
    );
  }
}

export default App;
